import { ref, reactive, computed } from 'vue';

export function useVideoProcessing() {
  const videoFile = ref(null);
  const sourceVideo = ref(null);
  const isProcessing = ref(false);
  const progressValue = ref(0);
  const currentTime = ref(0);
  const frames = ref([]);
  const frameCounter = ref(0);
  const statusMessage = ref('等待选择视频文件');
  const videoDimensions = ref({ width: 0, height: 0 });

  const cropParams = ref({
    left: 0,
    top: 0,
    width: 100,
    height: 100
  });

  const canvas = ref(null);
  const ctx = ref(null);

  // 处理视频文件
  const processFile = (file) => {
    videoFile.value = file;
    statusMessage.value = '视频已加载，准备处理';

    // 创建临时视频对象获取元数据
    const tempVideo = document.createElement('video');
    tempVideo.src = URL.createObjectURL(file);

    tempVideo.onloadedmetadata = () => {
      // 更新视频尺寸
      videoDimensions.value = {
        width: tempVideo.videoWidth,
        height: tempVideo.videoHeight
      };

      // 设置默认裁剪参数
      cropParams.value = {
        left: 0,
        top: 0,
        width: tempVideo.videoWidth,
        height: tempVideo.videoHeight
      };

      // 更新视频源
      if (sourceVideo.value) {
        sourceVideo.value.src = tempVideo.src;
      }
    };
  };

  // 初始化画布
  const initCanvas = () => {
    canvas.value = document.createElement('canvas');
    ctx.value = canvas.value.getContext('2d', { willReadFrequently: true });
    
    if (videoDimensions.value.width > 0) {
      canvas.value.width = videoDimensions.value.width;
      canvas.value.height = videoDimensions.value.height;
    }
  };

  // 重置处理状态
  const resetProcessing = () => {
    isProcessing.value = false;
    progressValue.value = 0;
    currentTime.value = 0;
    frames.value = [];
    frameCounter.value = 0;
  };

  return {
    videoFile,
    sourceVideo,
    isProcessing,
    progressValue,
    currentTime,
    frames,
    frameCounter,
    cropParams,
    videoDimensions,
    statusMessage,
    canvas,
    ctx,
    processFile,
    initCanvas,
    resetProcessing
  };
}